package com.bah.tract.security;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * Provides access to a user's WindowsStore from a Singleton. This avoids
 * loading the KeyStore multiple times.
 */
public final class WindowsKeystore {

	/**
	 * Reference to a user's Windows KeyStore.
	 * 
	 * @uml.property name="keystore"
	 */
	private static KeyStore keystore;

	/**
	 * Loads an the user's Windows KeyStore.
	 */
	static {
		try {
			keystore = KeyStore.getInstance("Windows-MY");
			// Note: When a security manager is installed,
			// the following call requires SecurityPermission
			// "authProvider.SunMSCAPI".
			keystore.load(null, null);
		} catch (final GeneralSecurityException e) {
			throw new RuntimeException(e);
		} catch (final IOException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * Retrieves the certificate aliases contained in the user's Windows
	 * KeyStore.
	 * 
	 * @return An array of aliases or an empty array if no alias were found.
	 */
	public static String[] getAliases() {
		try {
			final List<String> aliases = new ArrayList<String>();
			final Enumeration<String> e = keystore.aliases();
			while (e.hasMoreElements()) {
				aliases.add(e.nextElement());
			}
			return aliases.toArray(new String[aliases.size()]);
		} catch (final KeyStoreException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * Provides access to the Window's KeyStore.
	 * 
	 * @return An initialized KeyStore.
	 * @uml.property name="keystore"
	 */
	public static KeyStore getKeystore() {
		return keystore;
	}

	/**
	 * Private constructor to avoid creation of multiple instances.
	 */
	private WindowsKeystore() {

	}
}
